#ifndef SCATTERPLOTMODEL_HPP
#define SCATTERPLOTMODEL_HPP

#include <QObject>
#include <QDateTime>
#include <QList>
#include <QDebug>
#include <QPointer>
#include "store/type/MetaMoldType.hpp"
#include "store/struct/Basic.hpp"
#include "store/struct/Synthetic.hpp"
#include "store/struct/LadderLineCarrier.hpp"
#include "store/Huben.hpp"
#include "tool/Tool.hpp"

class LadderLineChartModel : public QObject {
    Q_OBJECT

public:
    explicit LadderLineChartModel(QObject *parent = nullptr) : QObject(parent) {


        QPointer<LadderLineChartModel> weakPtr(this);

        // 在 lambda 中捕获 weakPtr
        Huben::instance().registerStateChangedHandler(ActionWrapper::StateKey::Synthetic, [weakPtr](const QVariant &value) {
            if (!weakPtr) return;

            if (value.canConvert<Synthetic>()) {

                Synthetic synthetic = value.value<Synthetic>();
                weakPtr-> setLadderLines(synthetic.ladderLines);
                weakPtr-> setStartTime(synthetic.startTime);
                weakPtr-> setEndTime(synthetic.endTime);

            } else {
                qWarning() << "Received QVariant cannot be converted to Synthetic";
            }
        });

        // 初始请求数据
        Huben::instance().dispatch(ActionWrapper::ActionType::InitModify, QVariant::fromValue(MetaMoldType::TimeSequence));
    }

    QList<LadderLineCarrier> getLadderLines() const {
        return ladderLines;
    }

    // 设置 ladderLinesChanged 数据
    void setLadderLines(const QList<LadderLineCarrier>& newLadderLines) {
        if (ladderLines != newLadderLines) {
            ladderLines = newLadderLines;
            emit ladderLinesChanged(ladderLines);
        }
    }

    // 获取开始时间
    QDateTime getStartTime() const {
        return startTime;
    }

    // 获取结束时间
    QDateTime getEndTime() const {
        return endTime;
    }

    void setStartTime(const QDateTime& newStartTime) {
        if (!newStartTime.isValid()) {
            qWarning() << "Invalid QDateTime received in newStartTime";
            return;
        }

        if (startTime != newStartTime) {
            startTime = newStartTime;
            emit startTimeChanged(startTime); // 这里加上发射信号
        }
    }

    void setEndTime(const QDateTime& newEndTime) {
        if (!newEndTime.isValid()) {
            qWarning() << "Invalid QDateTime received in newEndTime";
            return;
        }
        if (endTime != newEndTime) {
            endTime = newEndTime;
            emit endTimeChanged(endTime);     // 这里加上发射信号
        }
    }


signals:
    void startTimeChanged(const QDateTime &newStartTime);
    void endTimeChanged(const QDateTime &newEndTime);
    void ladderLinesChanged(const QList<LadderLineCarrier> &ladderLines);

private:
    QList<LadderLineCarrier> ladderLines;
    QDateTime startTime;
    QDateTime endTime;
};

#endif // SCATTERPLOTMODEL_HPP
